package com.topscomm.pm.script;

import cn.hutool.core.date.DateUnit;
import com.topscomm.basic.BasicEntity;
import com.topscomm.basic.exception.ServiceException;
import com.topscomm.basic.util.SQLAdapter;
import com.topscomm.cbo.pojo.CboApprovalNodeInsEntity;
import com.topscomm.cbo.pojo.CboDeptEntity;
import com.topscomm.cbo.pojo.CboOrgEntity;
import com.topscomm.cbo.pojo.CboUserEntity;
import com.topscomm.cbo.service.impl.CboDeptService;
import com.topscomm.cbo.service.impl.CboOrgService;
import com.topscomm.cbo.service.impl.CboUserService;
import com.topscomm.pm.PmScript;
import com.topscomm.pm.pojo.PmTaskEntity;
import com.topscomm.pm.pojo.PmTaskLogEntity;
import com.topscomm.pm.service.impl.PmTaskLogService;
import com.topscomm.pm.service.impl.PmTaskService;
import com.topscomm.pub.util.ConvertUtil;
import com.topscomm.pub.util.DateUtil;
import com.topscomm.pub.util.SpringUtil;
import com.topscomm.pub.util.StringBufferProxy;
import com.topscomm.tap.ITapService;
import com.topscomm.tap.TapEntity;
import com.topscomm.tap.common.FlowDatacodeCache;
import com.topscomm.tap.common.SessionUserBean;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

public class PmTaskScript extends PmScript {

    /**
     * @author: wushenghong
     * @date: 2020/6/4
     * @description: 任务状态更新
     */


    public void updateTaskStateToEnd(ITapService service, TapEntity entity) throws Exception {
        // 审批节点实例
        CboApprovalNodeInsEntity nodeIns = (CboApprovalNodeInsEntity) entity;
        String sourceId = ConvertUtil.convertToString(nodeIns.getSourceid());
        PmTaskService pmTaskService = (PmTaskService) SpringUtil.getBean("pmTaskService");
        PmTaskEntity pmTaskEntity = pmTaskService.queryById(sourceId);
        Date today = DateUtil.getZreoOfDay(new Date());
        if (pmTaskEntity != null) {
            pmTaskEntity.setTaskstate("4");
            pmTaskEntity.setActualendtime(today);
            pmTaskService.updateEntity(pmTaskEntity);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void updateTaskStateToStart(ITapService service, TapEntity entity) throws Exception {
        // 审批节点实例
        CboApprovalNodeInsEntity nodeIns = (CboApprovalNodeInsEntity) entity;
        String sourceId = ConvertUtil.convertToString(nodeIns.getSourceid());
        PmTaskService pmTaskService = (PmTaskService) SpringUtil.getBean("pmTaskService");
        PmTaskEntity pmTaskEntity = pmTaskService.queryById(sourceId);
        if (pmTaskEntity != null) {
            String taskState = pmTaskEntity.getTaskstate();
            if ("2".equals(taskState)) {// 任务已发布,点击任务开始
                pmTaskEntity.setTaskstate("3");
                pmTaskService.updateEntity(pmTaskEntity);
                //判断任务实际开始日期是否包含当天
                Date actualStartTime = DateUtil.getZreoOfDay(pmTaskEntity.getActualstarttime());
                Date today = DateUtil.getZreoOfDay(new Date());
                if (cn.hutool.core.date.DateUtil.between(actualStartTime, today, DateUnit.DAY, false) == 0) {
                    // 创建当天的工作日志
                    creatTheSameDayTaskLog(pmTaskEntity);
                }
            }
        }
    }

    //工作日志信息生成
    @Transactional(rollbackFor = Exception.class)
    public void creatTheSameDayTaskLog(PmTaskEntity entity) throws ServiceException {
        //日志插入及提交
        String taskLogDay = cn.hutool.core.date.DateUtil.formatDate(entity.getActualstarttime());
        PmTaskLogService pmTaskLogService = (PmTaskLogService) SpringUtil.getBean("pmTaskLogService");
        FlowDatacodeCache flowDatacodeCache = (FlowDatacodeCache) SpringUtil.getBean("flowDatacodeCache");
        List<BasicEntity> entities = new ArrayList<>();
        // 避免重复插入判断
//        StringBufferProxy sql = new StringBufferProxy();
//        sql.appendSingle("taskid = {0} and finishtime = {1}", entity.getId(), SQLAdapter.toDateLong(taskLogDay + " 00:00:00"));
//        List<PmTaskLogEntity> pmTaskLogEntityList = pmTaskLogService.queryByWhere(sql.toString());
//        sql.clear();
        // 当天是工作日且未生成工作日志
        if (pmTaskLogService.isWorkDate(entity.getProjectid(), entity.getActualstarttime())) {
            // 任务负责人信息
            String leaderCode = entity.getLeadercode();
            String leaderName = entity.getLeadername();
            if (leaderCode == null || leaderName == null) {
                throw new ServiceException("当前任务中任务负责人信息不可以为空！");
            }
            // 任务参与人信息
            String participantCodes = entity.getParticipantcodes();
            String participantNames = entity.getParticipantnames();
            // 任务相关人信息，包含负责人及参与人
            List<String> participantCodeListTemp = new ArrayList<String>();
            List<String> participantNameListTemp = new ArrayList<String>();
            //任务参与人添加至相关人
            if (participantCodes != null && participantNames != null) {
                participantCodeListTemp = Arrays.asList(participantCodes.split(","));
                participantNameListTemp = Arrays.asList(participantNames.split(","));
            }
            //调用Arrays.asList()生产的List的add、remove方法时报异常,这样转换处理
            List<String> participantCodeList = new ArrayList<String>(participantCodeListTemp);
            List<String> participantNameList = new ArrayList<String>(participantNameListTemp);
            //任务负责人添加至相关人
            participantCodeList.add(leaderCode);
            participantNameList.add(leaderName);
            // 姓名、工号不对应则结束
            if (participantCodeList.size() != participantNameList.size()) {
                throw new ServiceException("当前任务中任务相关人姓名、工号信息不对应，请联系系统管理员！");
            }
            // 创建日志单据
            Map<String, Object> orgAndDeptMap = new HashMap<>();
            Map<String, Object> taskLogApplyMap = new HashMap<>();
            List<Map<String, Object>> flowidList = new ArrayList<>();
            for (int i = 0; i < participantCodeList.size(); i++) {
                // 避免重复插入
                StringBufferProxy sql = new StringBufferProxy();
                sql.appendSingle("taskid = {0} and finishtime = {1} and  usercode = '{2}'",  entity.getId(), SQLAdapter.toDateLong(taskLogDay + " 00:00:00"), participantCodeList.get(i));
                List<PmTaskLogEntity> pmTaskLogEntityList = pmTaskLogService.queryByWhere(sql.toString());
                sql.clear();
                if (pmTaskLogEntityList.size() != 0) {
                    continue;
                }
                orgAndDeptMap = pmTaskLogService.queryOrgAndDeptByCode(participantCodeList.get(i));
                flowidList = flowDatacodeCache.getApprovalFlowListMap("ApprovalFlow_PmTaskLog", participantCodeList.get(i), "sortcode");
                PmTaskLogEntity pmTaskLogEntity = new PmTaskLogEntity();
                taskLogApplyMap.put("projectid", entity.getProjectid());
                taskLogApplyMap.put("taskid", entity.getId());
                taskLogApplyMap.put("name", entity.getName());
                taskLogApplyMap.put("type", entity.getTasktype());
                taskLogApplyMap.put("content", entity.getExplain());
                taskLogApplyMap.put("finishtime", taskLogDay);
                taskLogApplyMap.put("username", participantNameList.get(i));
                taskLogApplyMap.put("usercode", participantCodeList.get(i));
                taskLogApplyMap.put("orgcode", orgAndDeptMap.get("orgcode"));
                taskLogApplyMap.put("orgname", orgAndDeptMap.get("orgname"));
                taskLogApplyMap.put("deptcode", orgAndDeptMap.get("deptcode"));
                taskLogApplyMap.put("deptname", orgAndDeptMap.get("deptname"));
                taskLogApplyMap.put("docdate", taskLogDay);
                taskLogApplyMap.put("flowid", flowidList.size() > 0 ? flowidList.get(0).get("id") : 0);
                pmTaskLogEntity.convertFromMap(taskLogApplyMap);
                entities.add(pmTaskLogEntity);
                taskLogApplyMap.clear();
                orgAndDeptMap.clear();
                flowidList.clear();
            }
        }
        // 批量插入并提交
        if (entities.size() > 0) {
            pmTaskLogService.insertBatch(entities);
            // 系统session
            CboUserService cboUserService = (CboUserService) SpringUtil.getBean("cboUserService");
            CboDeptService cboDeptService = (CboDeptService) SpringUtil.getBean("cboDeptService");
            CboOrgService cboOrgService = (CboOrgService) SpringUtil.getBean("cboOrgService");
            List<CboUserEntity> cboUserEntities = cboUserService.queryByWhere(" code = 'QuartzUser' ");
            List<CboDeptEntity> cboDeptEntities = cboDeptService.queryByWhere(" code = 'D11803'");
            List<CboOrgEntity> cboOrgEntities = cboOrgService.queryByWhere(" code ='D1'");
            SessionUserBean sessionUserBean = new SessionUserBean();
            if (cboUserEntities.size() > 0 && cboDeptEntities.size() > 0 && cboOrgEntities.size() > 0) {
                sessionUserBean.setUser(cboUserEntities.get(0));
                sessionUserBean.setDept(cboDeptEntities.get(0));
                sessionUserBean.setWorkDept(cboDeptEntities.get(0));
                sessionUserBean.setOrg(cboOrgEntities.get(0));
                sessionUserBean.setWorkOrg(cboOrgEntities.get(0));
            }
            // 遍历提交单据
            for (BasicEntity pmTaskLogEntity : entities) {
                // 赋值单号及提交时间
                String docNo = String.valueOf(pmTaskLogEntity.getId());
                docNo = docNo.substring(0, 6) + docNo.substring(9);
                pmTaskLogEntity.setValue("docno", docNo);
                pmTaskLogEntity.setValue("submitdate", new Date());
                Map<String, Object> dataMap = pmTaskLogEntity.convertToMap();
                StringBufferProxy mailtitle = new StringBufferProxy();
                mailtitle.appendSingle("{0}的工作日志待提交，任务：{1}",
                        DateUtil.dateToString(ConvertUtil.convertToDate(dataMap.get("finishtime")), "yyyy-MM-dd"), dataMap.get("name"));
                pmTaskLogService.executeSubmit((TapEntity) pmTaskLogEntity, mailtitle.toString(), sessionUserBean);
                mailtitle.clear();
            }
        }
    }
}
